package com.proposition.web.user;

import com.proposition.commons.model.User;
import com.proposition.support.annotation.LogAnnotation;
import com.proposition.support.annotation.Token;
import com.proposition.support.security.CurrentUser;
import com.proposition.support.utils.MyPasswordEncrypt;
import com.proposition.support.utils.Rest;
import com.proposition.support.utils.UUIDUtil;
import com.proposition.user.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * ${DESCRIPTION}
 *
 * @author 杨凯
 * @create 2017-10-27 9:35
 **/
@Controller
@RequestMapping("user")
public class UserController {

	private static final Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService userService;
	/**
	 *修改密码界面
	 * @return
	 */
	@GetMapping("/changePasswordPage")
	public String changePasswordPage(){
		return "user/change-password";
	}
	/**
	 *修改密码界面
	 * @return
	 */
	@LogAnnotation(moduleName = "用户模块", operate = "修改密码")
	@ResponseBody
	@PostMapping("/changePassword")
	public Rest changePassword(@RequestParam("oldPassword")String oldPassword,@RequestParam("newPassword") String newPassword,@RequestParam("confirmPassword")String confirmPassword){
		Rest.Builder rest = Rest.newBuilder();
		//获取当前用户信息
		User user = CurrentUser.INSTANCE.getUser();
		//判断用户密码输入是否正确
		if(!MyPasswordEncrypt.encryptPassword(oldPassword).equals(user.getPassword())){
			//原始密码不正确
			return rest.status(1003).build();
		}
		if(!newPassword.equals(confirmPassword)){
			//两次密码不一致
			logger.info("两次密码不一致[{}],[{}]",newPassword,confirmPassword);
			return rest.status(1002).build();
		}
		if(userService.changePassword(user.getId(),newPassword)){
			logger.info("密码修改成功！");
			return rest.status(1001).build();
		}
		return rest.status(1003).build();
	}
	/**
	 *  用户列表界面
	 * @return
	 */
	@RequiresRoles("admin")
	@GetMapping("/userListPage")
	public String userListPage(Model model){
		model.addAttribute("userList",userService.findUserList());
		return "user/user-list";
	}

	/**
	 * 添加用户界面
	 * @param model
	 * @return
	 */
	@Token(save = true)
	@GetMapping("/addUserPage")
	public String addUserPage(Model model){
		model.addAttribute("rolelist", userService.findRoleList());
		return "user/user-add";
	}

	/**
	 *  添加用户
	 * @param userName
	 * @param password
	 * @param confirmPassword
	 * @param realName
	 * @param telephone
	 * @param roleId
	 * @return
	 */
	@LogAnnotation(moduleName = "用户模块", operate = "添加用户")
	@Token(remove = true)
	@ResponseBody
	@RequestMapping(value = "/addUser", method = RequestMethod.POST)
	public Rest addUser(@RequestParam String userName,
	                    @RequestParam String password,
	                    @RequestParam String confirmPassword,
	                    @RequestParam String realName, @RequestParam String telephone,
	                    @RequestParam Integer roleId) {
		Rest.Builder rest = Rest.newBuilder();
		try {
			if (!password.equals(confirmPassword)) {
				// 两次密码不一致
				return rest.status(1001).build();
			}
			User user = new User();
			user.setId(UUIDUtil.getUUID());
			user.setUserName(userName);
			user.setPassword(MyPasswordEncrypt.encryptPassword(password));
			user.setRealName(realName);
			user.setTelephone(telephone);
			user.setRoleId(roleId);
			if (userService.addUser(user)) {
				return rest.status(1002).build();
			}
		} catch (Exception e) {
			logger.error("添加用户失败[{}]", e.getMessage());
			return rest.status(1003).build();
		}
		return rest.build();
	}

	/**
	 * 检出用户名是否存在
	 *
	 * @param userName
	 * @return
	 */
	@ResponseBody
	@PostMapping(value = "/checkUserExist")
	public Rest checkUserExist(@RequestParam String userName) {
		Rest.Builder rest = Rest.newBuilder();
		if (userService.checkUserExist(userName)) {
			return rest.status(1001).build();
		} else {
			return rest.status(1002).build();
		}
	}


	/**
	 * 修改用户资料界面
	 * @return
	 */
	@RequestMapping(value = "/updateUserPage", method = RequestMethod.GET)
	public String updateUserInfoPage(@RequestParam("userId") String userId, Model model){
		model.addAttribute("rolelist", userService.findRoleList());
		model.addAttribute("users", userService.findById(userId));
		return "user/user-update";
	}
	/**
	 * 修改用户资料
	 *
	 * @param userId
	 * @return
	 */
	@LogAnnotation(moduleName = "用户模块", operate = "修改用户资料")
	@ResponseBody
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public Rest updateUserInfo(@RequestParam String userId,
	                       @RequestParam String realName, @RequestParam String telephone,
	                       @RequestParam String roleId, @RequestParam String password) {
		Rest.Builder rest = Rest.newBuilder();
		//判断是否修改了密码
		if(!password.equals(CurrentUser.INSTANCE.getUser().getPassword())){
			password = MyPasswordEncrypt.encryptPassword(password);
		}
		boolean result = userService.updateUserInfo(userId, realName, password,
				roleId, telephone);
		if (result) {
			return rest.status(1001).build();
		}
		return rest.build();
	}

	/**
	 * 修改用户状态为禁用
	 *
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
	@ResponseBody
	public Rest deleteUser(@RequestParam("userId") String userId) {
		Rest.Builder rest = Rest.newBuilder();
		try {
			boolean status = userService.deleteUserById(userId);
			if (status) {
				return rest.status(1001).build();
			} else {
				logger.error("删除失败");
				return rest.status(1002).build();
			}
		} catch (Exception e) {
			logger.error("删除用户失败[{}]", e.getMessage());
		}
		return rest.build();
	}

}
